package com.gateway.video.rtsp.server.handler.support;

import com.gateway.video.rtsp.server.VideoServerConstants;
import com.gateway.video.rtsp.server.sdp.SdpServerCodec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.rtsp.RtspVersions;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.kohsuke.MetaInfServices;
import java.net.InetSocketAddress;
import java.time.LocalDateTime;

@Slf4j
@MetaInfServices(RtspRequest.class)
public class DescribeRtspRequest extends AbstractRtspRequest {
    @Override
    protected void doHanlder(ChannelHandlerContext ctx, HttpRequest request, Promise promise) {
        var remoteAddress = ((InetSocketAddress) ctx.channel().remoteAddress());

        var response = new DefaultFullHttpResponse(RtspVersions.RTSP_1_0, HttpResponseStatus.OK);
        response.headers().set(HttpHeaderNames.SERVER, VideoServerConstants.VIDEO_VERSION);
        response.headers().set(HttpHeaderNames.DATE, LocalDateTime.now());
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, RtspMediaType.SDP.getName());
        response.headers().set(HttpHeaderNames.CONTENT_BASE, "rtsp://" + remoteAddress.getHostString() + ":" + remoteAddress.getPort());
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache");
        response.headers().set(VideoServerConstants.CSEQ, request.headers().get(VideoServerConstants.CSEQ));

        /* 返回sdp会话级描述与媒体级描述 */
        ByteBuf buffer =SdpServerCodec.encode(ctx.alloc().buffer(), null, null);

        response.content().writeBytes(buffer);
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

        ctx.writeAndFlush(response, ctx.newPromise().addListener(future -> {
            if(future.isSuccess()) {
                promise.setSuccess(response);
            }else {
                promise.setFailure(future.cause());
            }
        }));
    }

    @Override
    public boolean isSupport(HttpRequest request) {
        return request.method().name().equals(RtspHttpMethod.DESCRIBE.name());
    }
}
